package org.geekbang.thinking.in.spring.conversion;

import org.geekbang.thinking.in.spring.conversion.event.pub.CustomEventPublisher;
import org.geekbang.thinking.in.spring.conversion.ioc.SpringIoc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

@Component
@ComponentScan
public class Application {
    private AnnotationConfigApplicationContext applicationContext;


    public Application() {
        // 构造函数中只初始化基本字段，不进行复杂操作
    }

    public void start() {
        try {
            // 创建应用上下文
            applicationContext = new AnnotationConfigApplicationContext(Application.class);

            System.out.println("应用上下文已启动...");

            // 注册关闭钩子，确保在JVM关闭时能触发ContextClosedEvent
            applicationContext.registerShutdownHook();

        } catch (Exception e) {
            System.err.println("启动应用上下文时出错: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public void close() {
        if (applicationContext != null && applicationContext.isActive()) {
            applicationContext.close();
        }
    }

    public static void main(String[] args) {
        Application application = new Application();
        application.start();
        // 在Spring完全初始化后执行
        application.sayHello();
        application.publishCustomEvent();

        // 关闭应用
        application.close();
    }

    private void sayHello() {
        SpringIoc springIoc = applicationContext.getBean("springIoc", SpringIoc.class);
        springIoc.sayHello();
    }


    private void publishCustomEvent() {
        CustomEventPublisher eventPublisher = applicationContext.getBean("customEventPublisher", CustomEventPublisher.class);

        if (eventPublisher != null) {
            eventPublisher.publishCustomEvent("Hello from Custom Event!");
        } else {
            System.out.println("Event publisher is not available");
        }
    }

}
